package com.campus.dao.impl;

import com.campus.common.StringUtils;
import com.campus.dao.UserDao;
import com.campus.model.User;
import com.campus.utils.PasswordUtil;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @desc: 用户数据访问对象实现类
 * @author: hjm
 * @date: 2024/11/22
 */
@Repository
public class UserDaoImpl implements UserDao {

    private final JdbcTemplate jdbcTemplate;

    // 构造函数注入JdbcTemplate
    public UserDaoImpl(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    /**
     * 用户登录验证
     * @param loginName 登录名
     * @param password 密码
     * @return 如果验证成功返回用户对象，否则返回null
     */
    @Override
    public User login(String loginName, String password) {
        String sql = "SELECT * FROM t_sys_user WHERE LOWER(login_name) = LOWER(?)";
        try {
            // 查询用户信息
            User user = jdbcTemplate.queryForObject(sql, new Object[]{loginName},
                    new BeanPropertyRowMapper<>(User.class));

            // 获取盐值并加密密码
            String salt = StringUtils.getSalt(loginName);
            String encryptedPassword = StringUtils.md5Encoder(password, salt);

            // 打印输入的密码和存储的密码以便调试
            System.out.println("输入的密码: " + password);
            System.out.println("加密后的密码: " + encryptedPassword);
            System.out.println("存储的密码: " + (user != null ? user.getPassword() : null));

            // 验证密码是否匹配
            if (user != null && encryptedPassword.equals(user.getPassword())) {
                return user;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 添加新用户
     * @param user 用户对象
     * @return 受影响的行数
     */
    @Override
    public int addUser(User user) {
        String sql = "INSERT INTO t_sys_user (login_name, password, gender, birthday, phone, email, status) " +
                "VALUES (?, ?, ?, ?, ?, ?, ?)";
        // 获取盐值并加密密码
        String salt = StringUtils.getSalt(user.getLoginName());
        String encryptedPassword = StringUtils.md5Encoder(user.getPassword(), salt);

        return jdbcTemplate.update(sql, user.getLoginName(), encryptedPassword, user.getGender(),
                user.getBirthday(), user.getPhone(), user.getEmail(), user.getStatus());
    }

    /**
     * 根据关键字查询用户
     * @param keyword 关键字
     * @return 符合条件的用户列表
     */
    @Override
    public List<User> queryUser(String keyword) {
        String sql = "SELECT * FROM t_sys_user WHERE login_name LIKE ? OR id = ?";
        return jdbcTemplate.query(sql, new Object[]{"%" + keyword + "%", keyword},
                new BeanPropertyRowMapper<>(User.class));
    }
}